﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MWTools.Client.Common.Interfaces;
using MWTools.Client.Common;

namespace MWTools.Client.Helpers
{
    internal class PluginHelpers
    {
        public static void SubmitItemToPlugin(string entryId, string xmlResult)
        {
            try
            {
                Assembly pluginAssembly = Assembly.LoadFrom(AppContext.Current.UserSetting.PluginAssembly);
                Type type = pluginAssembly.GetExportedTypes().First(m => m.FullName == AppContext.Current.UserSetting.CurrentPlugin);
                ContentSubmitterBase b =
                    type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null) as ContentSubmitterBase;

                b.SubmitContent(AppContext.Current.UserSetting.MWToolsServerUri,
                    AppContext.Current.UserSetting.UserName,
                    AppContext.Current.UserSetting.Password,
                    entryId,
                    xmlResult);


            }
            catch (System.Net.WebException exception)
            {
                Logger.DebugFormat("OutlookController.SubmitItemToWIki", "{0}", exception);
                throw;
            }
            catch (System.Exception ioException)
            {
                string assemblyLocation = Assembly.GetExecutingAssembly().Location;
                System.IO.FileInfo di = new System.IO.FileInfo(assemblyLocation);
                AppContext.Current.UserSetting.PluginAssembly = String.Format("{0}\\{1}", di.DirectoryName, "MWTools.Client.Plugins.dll");
                AppContext.Current.Save();
                try
                {
                    Logger.DebugFormat("OutlookController.SubmitItemToWIki", "{0}", ioException);
                    SubmitItemToPlugin(entryId, xmlResult);
                }
                catch (Exception ex)
                {
                    Logger.DebugFormat("OutlookController.SubmitItemToWIki", "{0}", ex);
                    throw;
                }

            }
        }


    }
}
